package com.test.shiro.relam;

import com.test.shiro.domain.PowerRepository;
import com.test.shiro.entity.User;
import com.test.shiro.entity.UserRole;
import com.test.shiro.service.PowerService;
import com.test.shiro.service.RolePowerService;
import com.test.shiro.service.UserRoleService;
import com.test.shiro.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Component
public class MyRealm extends AuthorizingRealm {
    @Autowired
    private UserService userService;
    @Autowired
    private UserRoleService userRoleService;
    @Autowired
    private RolePowerService rolePowerService;
    @Autowired
    private PowerService powerService;
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String username = token.getPrincipal().toString();
        String pwd = new String((char[]) token.getCredentials());
        System.out.println("========" + username + "===============" + pwd);
        List<User> userList = userService.findByUname(username);
        if (userList.isEmpty()) {
            return null;
        }
        User user = userList.get(0);

        AuthenticationInfo info = new SimpleAuthenticationInfo(token.getPrincipal(), user.getPwd(), ByteSource.Util.bytes("bjsxt"), token.getPrincipal().toString());

        return info;

    }


    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("认证开始");
        String username= (String) principalCollection.getPrimaryPrincipal();
        System.out.println("认证============"+username);
        User user=userService.findByUname(username).get(0);
        List<String> permissions=new ArrayList<>();
        List<UserRole> userRoles=userRoleService.findByUid(user.getUid());
        for(UserRole userRole:userRoles){
            List<Integer> pids=rolePowerService.findByRid(userRole.getRid()).stream().map(e->e.getPid()).collect(Collectors.toList());

            permissions.addAll(powerService.findPermissions(pids));
        }
        SimpleAuthorizationInfo simpleAuthorizationInfo=new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.addStringPermissions(permissions);
        return simpleAuthorizationInfo;
    }
}
